/**
 * Dear programmer:
 * When I wrote this code, only god and I knew how it worked.
 * Now, only god knows it!
 *
 * @author: Pegasus  Date: 2018/11/21 Time: 10:06
 *
 * 个人中心
 */

import React, {Component} from 'react';
import {
    Linking,TextInput,
    SafeAreaView,
    ScrollView,
    TouchableOpacity,
    View,
    TouchableHighlight,
    Text,
    Platform,
    BackHandler,
    ToastAndroid,
    Modal,Image
} from 'react-native';
import {connect} from 'react-redux';
import {styles} from './AssignRoom.Style';
import {
    COLOR_FOCUS,
    COLOR_GRAY_BACKGROUND,
    COLOR_LINK,
    FONT_COLOR_SUB_TITLE,
    FONT_COLOR_TITLE
} from "../../../constant/PHColors";
import SideMenu from 'react-native-side-menu';
import {SCREEN_WIDTH} from "../../../constant/PHScreen";
import {dailyOrderSweepDefault, onRetrieveRoomsViewAs, retrieveRoomsViewAs,dailyOrderSweepSave} from "./Actions"
import {FetchStatus} from "../../../configuration/RequestConfiguration";
import {ReturnStatus} from "../../../configuration/ReturnStatus";
import {doDisplaySuccessMessage, doDisplayWarnMessage} from "../../../component/Message/Action";
import ScrollTabView from "../../../component/ScrollTabView/ScrollTabView";
import AntDesign from "react-native-vector-icons/AntDesign";
import MaterialIcons from "react-native-vector-icons/MaterialIcons"
import SelectFromBottomPlugIn from "../../custom/selectFromBottom/selectFromBottomPlugIn";
import FontAwesome from "react-native-vector-icons/FontAwesome";
import LoadingView from "../../../component/LoadingView/LoadingView";
import {DefaultTabBar} from "react-native-scrollable-tab-view";
import ScrollableTabView from "react-native-scrollable-tab-view";
import {cancelSweepOrder} from "../../RoomDisk/RoomStatus/RoomStatusBranch/Actions";

class AssignRoom extends Component {

    static navigationOptions = ({navigation}) => ({
        headerTitle: ``,
        headerLeft: <View><Text style={{marginLeft:15,fontSize:18,color:FONT_COLOR_TITLE}}>分配做房</Text></View>,
        headerRight: (
            <TouchableOpacity activeOpacity={0.9} onPress={navigation.getParam('addClick')}>
                <View style={{width: 80, height: 44, flexDirection: 'row', justifyContent: 'center', alignItems: 'center'}}>
                    <Text style={{fontSize:17,color:FONT_COLOR_TITLE}}>
                        保存
                    </Text>
                </View>
            </TouchableOpacity>
        ),

    });

    // 构造
    constructor(props) {
        super(props);

        this.buildingSel = [];
        this.buildingArr = [];
        this.props.onCache.building.map((item,index)=>{
            this.buildingSel.push(item);
            this.buildingArr.push(item.descript1);
        });
        // console.log(JSON.stringify( this.buildingArr))

        this.wuseridSel = [];
        this.wuseridArr = [];

        this.conditionArr = ["设置自动分房起点","调整做房分值"];
        this.conditionRoom = {};

        this.assConditionArr = ["撤销"];

        // 初始状态
        this.state = {
            showClean:false,
            dailywuserid:[],      //清洁人数组
            view_wuserid:{},        //是否显示view
            roomsArr:[],        //房间信息
            showTypePop: false,
            showAssPop: false,
            buildingSelIndex:0,
            buildingSelName: this.buildingArr[0],             //打扫时间名称
            showWuseridPop: false,
            wuseridSelIndex:0,
            wuseridSelName: this.wuseridArr[0],             //选择清洁人
            showConditionPop: false,
            flag:'',
            changeQtyVisible:false, // 修改做房分值
            changeQtyNum:0,
            room_wuserid:{},        //左面清洁人的房间
            select_rooms:{},
            select_floors:[],
            synstatus:'ALL',        //查询条件 根据房间状态
        };
        this.rooms = {}; //右边房号
        this.floors = {};//右边楼层
        this.selected_room = [];
        this.qty_avg = 0;
    }



    componentWillReceiveProps(nextProps, nextContext): void {
        let {dispatch} = this.props;

        if (nextProps.onDailyOrderSweepDefault !== this.props.onDailyOrderSweepDefault && nextProps.onDailyOrderSweepDefault.fetchStatus === FetchStatus.Success) {
            if (nextProps.onDailyOrderSweepDefault.RETURN === ReturnStatus.Success) {
                let dailywuserid = nextProps.onDailyOrderSweepDefault.dailywuserid;
                let view_wuserid = {};
                let room_wuserid = {};
                dailywuserid.map((item,index)=>{
                    this.wuseridSel.push(item);
                    this.wuseridArr.push(item.wusername);
                    view_wuserid[item.wuserid] = (index===0?'true':'false')
                    room_wuserid[item.wuserid] = []
                });
                this.setState({
                    dailywuserid:dailywuserid,
                    view_wuserid:view_wuserid,
                    room_wuserid:room_wuserid,
                });

            } else {
                dispatch(doDisplayWarnMessage(nextProps.onDailyOrderSweepDefault.MSG))
            }

            let str = {"wherestatus":{"All":"1"},"arg":{"arg":"房务"},"where":{"building":"","rmtype":"","floor":"","allSearch":"","source":"","market":"","features":"","grno":""}};
            dispatch(retrieveRoomsViewAs(JSON.stringify(str)));
        }

        if (nextProps.onRetrieveRoomsViewAs !== this.props.onRetrieveRoomsViewAs && nextProps.onRetrieveRoomsViewAs.fetchStatus === FetchStatus.Success) {
            if (nextProps.onRetrieveRoomsViewAs.RETURN === ReturnStatus.Success) {
                let data = nextProps.onRetrieveRoomsViewAs.DATA;


                let room_wuserid_json = this.state.room_wuserid;
                data.map((item,index)=>{
                    if(item['wuserid']&&item['wuserid']!=="" && item.whsk_status !=="撤销"){
                        if(room_wuserid_json[item['wuserid']]){
                            room_wuserid_json[item['wuserid']].push(item);
                        }else{
                            room_wuserid_json[item['wuserid']]=[item];
                        }
                    }
                });

                let qty_avg = 0;

                for(let i = 0; i < data.length; i++ ){
                    let item = data[i];
                    if( (!item['wuserid'] || item['wuserid']==='' || item.whsk_status ==="撤销" ) && this.selected_room.indexOf(item.room)<0 ) {
                        if (item.hsk_status !== "CL" && item.hsk_status !== "OS" && item.hsk_status !== "OO" && item.hsk_status !== "TU") {
                            qty_avg = qty_avg + Number(item.qty)
                        }
                    }
                }
                this.qty_avg = qty_avg/this.state.dailywuserid.length;

                this.setState({
                    roomsArr:data,
                    room_wuserid:room_wuserid_json,
                });
            } else {
                dispatch(doDisplayWarnMessage(nextProps.onRetrieveRoomsViewAs.MSG))
            }
        }

        if (nextProps.onDailyOrderSweepSave !== this.props.onDailyOrderSweepSave && nextProps.onDailyOrderSweepSave.fetchStatus === FetchStatus.Success) {
            if (nextProps.onDailyOrderSweepSave.RETURN === ReturnStatus.Success) {
                ToastAndroid.show(nextProps.onDailyOrderSweepSave.MSG,1000)
                this.props.navigation.state.params.callBack();
            } else {
                dispatch(doDisplayWarnMessage(nextProps.onDailyOrderSweepSave.MSG))
            }
        }

        if (nextProps.onChangeSweepOrderStatus !== this.props.onChangeSweepOrderStatus && nextProps.onChangeSweepOrderStatus.fetchStatus === FetchStatus.Success) {
            if (nextProps.onChangeSweepOrderStatus.RETURN === ReturnStatus.Success) {
                let newRoomsArr = [];
                console.log(JSON.stringify(this.assRoom))
                this.state.roomsArr.map((item,index)=>{
                    if( item.room === this.assRoom ) {
                        item.whsk_status = "撤销";
                    }
                    newRoomsArr.push(item)
                })

                for(let wuserid in this.state.room_wuserid){
                    this.state.room_wuserid[wuserid] = []
                }

console.log(JSON.stringify(newRoomsArr))
                let room_wuserid_json = this.state.room_wuserid;
                newRoomsArr.map((item,index)=>{
                    if(item['wuserid']&&item['wuserid']!=="" && item.whsk_status !=="撤销"){
                        if(room_wuserid_json[item['wuserid']]){
                            room_wuserid_json[item['wuserid']].push(item);
                        }else{
                            room_wuserid_json[item['wuserid']]=[item];
                        }
                    }
                });

console.log(JSON.stringify(this.state.room_wuserid))
                this.setState({
                    roomsArr:newRoomsArr,
                    room_wuserid:room_wuserid_json,
                })
            } else {
                dispatch(doDisplayWarnMessage(nextProps.onChangeSweepOrderStatus.MSG))
            }
        }



    }

    componentWillMount() {
        this.props.navigation.setParams({addClick: this.add_button});
    };

    add_button=()=>{
        let {dispatch} = this.props;

        console.log(this.state.select_rooms)

        if(JSON.stringify(this.state.select_rooms)==='{}' || JSON.stringify(this.state.select_rooms)==='[]'){
            let date = [];
            for(let wuserid in this.state.room_wuserid){
                this.state.room_wuserid[wuserid].map((item,index)=>{
                    date.push({"room":item.room,"wuserid":wuserid,"qty":item.qty,"wtype":item.wtype})
                })
            }
            let outJson = {"arg":{},"data":date};

            dispatch(dailyOrderSweepSave(JSON.stringify(outJson)));
        }else{
            ToastAndroid.show('已选择的房间未全部分配',1000)
        }

    };

    // 组件渲染后调用
    componentDidMount() {
        let {dispatch} = this.props;

        let str = {"arg":{}};
        dispatch(dailyOrderSweepDefault(JSON.stringify(str)));
    }


    render() {
        // let menu = this.showRoomList();
        if(this.state.roomsArr.length>0){
            return (
                <View style={{flex: 1}}>
                    <ScrollableTabView
                        prerenderingsiblingsNumber={1}
                        // page={this.state.page}
                        tabBarUnderlineColor="#5897FE"
                        tabBarTextStyle={{
                            fontSize:18
                        }}
                        tabBarUnderlineStyle={{backgroundColor:'#5897FE',height:2}}
                        tabBarActiveTextColor="#5897FE"
                        style={styles.ScrollableTabView}
                        renderTabBar={() => <DefaultTabBar style={{backgroundColor:COLOR_GRAY_BACKGROUND}}/>}
                    >
                        {
                            this.showRoomList()
                        }
                        {
                            (this.state.dailywuserid.length > 0)
                                ?
                                (
                                    <View tabLabel={'清洁人'} style={{flex:1}} >
                                        <SafeAreaView style={styles.container}>
                                            <ScrollView>
                                                {
                                                    this.state.dailywuserid.map((item,index)=>{
                                                        return this.showWuser(item,index);
                                                    })
                                                }
                                            </ScrollView>
                                        </SafeAreaView>
                                    </View>
                                )
                                :
                                (
                                    <View tabLabel={'清洁人'} style={styles.body} >
                                        <SafeAreaView style={styles.container}>
                                            <View  style={styles.windowCenter}>
                                                <View>
                                                    <Text style={styles.headerText}>
                                                        暂无值班人
                                                    </Text>
                                                </View>
                                                <TouchableOpacity activeOpacity={0.9} onPress={()=>{
                                                    this.props.navigation.navigate('StaffSchedule')
                                                }}>
                                                    <View style={{marginTop:3}}>
                                                        <Text style={[styles.headerText,{textDecorationLine:'underline',textDecorationStyle:'solid',fontSize:15}]}>
                                                            点击添加
                                                        </Text>
                                                    </View>
                                                </TouchableOpacity>
                                            </View>
                                        </SafeAreaView>
                                    </View>
                                )
                        }

                    </ScrollableTabView>

                    <SelectFromBottomPlugIn entityList={this.wuseridArr} checkedIndex={this.state.wuseridSelIndex} callback={(i) => {
                        let wuserid = this.wuseridSel[i]['wuserid'];
                        let room_wuserid = this.state.room_wuserid;
                        for(let room in this.state.select_rooms){
                            console.log(JSON.stringify(this.state.select_rooms[room]['wuserid']))

                            if(this.state.select_rooms[room]['wuserid'] && this.state.select_rooms[room]['wuserid']!==""){
                                let new_arr = []
                                for(let index in room_wuserid[this.state.select_rooms[room]['wuserid']]){
                                    if(room_wuserid[this.state.select_rooms[room]['wuserid']][index]['room'] !== room){
                                        new_arr.push(room_wuserid[this.state.select_rooms[room]['wuserid']][index])
                                    }
                                }
                                room_wuserid[this.state.select_rooms[room]['wuserid']] = new_arr
                            }
                            this.state.select_rooms[room]['wuserid'] = wuserid;
                            room_wuserid[wuserid].push(this.state.select_rooms[room]);
                            this.selected_room.push(room);
                        }
                        this.setState({
                            room_wuserid: room_wuserid,
                            select_rooms:[],
                            flag:'',
                        })
                    }} show={this.state.showWuseridPop} closeModal={(show) => {
                        this.setState({
                            select_rooms:{},
                            showWuseridPop: show
                        })
                    }}/>

                    <SelectFromBottomPlugIn entityList={this.assConditionArr} callback={(i) => {
                        switch (i) {
                            case 0 :
                                let select_rooms_json = this.state.select_rooms;


                                for(let room in select_rooms_json){

                                    this.assRoom = room;

                                    let orderid = select_rooms_json[room]['orderid'];
                                    let {dispatch} = this.props;

                                    let str = {"whsk_Order_Sweep_event":{"orderid":orderid,"remark":''},"whsk_Order_event":{"operation":"撤销"}};
                                    dispatch(cancelSweepOrder(JSON.stringify(str)));
                                }


                                break;
                            case 1 :
                                break;
                        }
                    }} show={this.state.showAssPop} closeModal={(show) => {
                        this.setState({
                            select_rooms:{},
                            showAssPop: show
                        })
                    }}/>
                </View>


            )
        }else{
            return <LoadingView/>
        }

    };

    //显示房间列表
    showRoomList(){
        this.rooms = {};
        this.floors = {};
        return(
            <View tabLabel={'房间'} style={[styles.body,{flex: 1}]} >
                <View style={styles.roomList}>
                    <View style={styles.buildingBox}>
                        <FontAwesome name={'building-o'} size={17} style={{color: COLOR_LINK,marginRight:4}}/>
                        <TouchableOpacity  activeOpacity={0.8}  onPress={() => this._openTypeDialog()} underlayColor="#4a65ff">
                            <Text style={{fontSize:17,color:COLOR_LINK}}>{this.state.buildingSelName}</Text>
                        </TouchableOpacity>
                    </View>

                    <View style={styles.roomStatusBox}>
                        {
                            this.showRoomStatusHtml()
                        }
                    </View>

                    <ScrollView style={styles.floorScroll}>
                        <View style={styles.floorBox}>
                            {
                                this.state.roomsArr.map((item,index)=>{
                                    return this.showRoomListHtml(item,index)
                                })
                            }
                        </View>
                    </ScrollView>

                    <View style={styles.buildingBottomView}>
                        <TouchableOpacity  activeOpacity={0.8}  onPress={() => {
                            // alert(this.state.select_rooms)
                            this._openWuseridDialog();
                        }} underlayColor="#4a65ff">
                            <View style={styles.buildingBottom}>
                                <Text style={styles.buildingBottomText}>
                                    添加到
                                </Text>
                            </View>
                        </TouchableOpacity>
                        <TouchableOpacity  activeOpacity={0.8}  onPress={() => {
                            this.setState({
                                showClean:!this.state.showClean,
                            })
                        }} underlayColor="#4a65ff">
                            <View style={styles.buildingBottom}>
                                <Text style={[styles.buildingBottomText,{color:FONT_COLOR_SUB_TITLE}]}>
                                    {
                                        this.state.showClean?'收起':'其他房间'
                                    }
                                </Text>
                            </View>
                        </TouchableOpacity>
                    </View>


                    {/*<SelectFromBottomPlugIn entityList={this.wuseridArr} checkedIndex={this.state.wuseridSelIndex} callback={(i) => {*/}
                        {/*let wuserid = this.wuseridSel[i]['wuserid'];*/}
                        {/*let room_wuserid = this.state.room_wuserid;*/}
                        {/*for(let room in this.state.select_rooms){*/}
                            {/*room_wuserid[wuserid].push(this.state.select_rooms[room]);*/}
                            {/*this.selected_room.push(room);*/}
                        {/*}*/}
                        {/*this.setState({*/}
                            {/*room_wuserid: room_wuserid,*/}
                            {/*select_rooms:[],*/}
                        {/*})*/}
                    {/*}} show={this.state.showWuseridPop} closeModal={(show) => {*/}
                        {/*this.setState({*/}
                            {/*showWuseridPop: show*/}
                        {/*})*/}
                    {/*}}/>*/}

                    <SelectFromBottomPlugIn entityList={this.buildingArr} checkedIndex={this.state.buildingSelIndex} callback={(i) => {
                        this.setState({
                            buildingSelIndex: i,
                            buildingSelName: this.buildingSel[i]['descript1'],
                        })
                    }} show={this.state.showTypePop} closeModal={(show) => {
                        this.setState({
                            showTypePop: show
                        })
                    }}/>

                    <SelectFromBottomPlugIn entityList={this.conditionArr}  callback={(i) => {
                        switch (i) {
                            case 0 :
                                // alert(JSON.stringify(this.conditionRoom))
                                this.setState({
                                    flag:this.conditionRoom.room,
                                });
                                break;
                            case 1 :
                                this.setState({
                                    changeQtyVisible:true,
                                })
                                break;
                        }
                    }} show={this.state.showConditionPop} closeModal={(show) => {
                        this.setState({
                            showConditionPop: show
                        })
                    }}/>

                    <Modal visible={this.state.changeQtyVisible} animationType = {'none'} transparent = {true} onRequestClose={()=> this.onRequestClose()} >
                            <View style={styles.checkmodalContainer} >
                                <View style={styles.checkModalBody}>
                                    <View style={[styles.checkModalHeader,{height:40}]}>
                                        <Text style={{color:COLOR_LINK,fontSize:18}}>
                                            调整做房分值
                                        </Text>
                                    </View>
                                    <View style={styles.checkModalHeader}>
                                        <TextInput style={styles.modalInput}
                                                   keyboardType='numeric'
                                                   textAlign='center'
                                                   autoFocus={true}
                                                   onChangeText={text => {
                                                       this.state.changeQtyNum = Number(text)
                                                   }}
                                        />
                                    </View>
                                    <View style={styles.checkModalCenter}>
                                        <TouchableOpacity  style={styles.checkModalCenterLeft} onPress={()=>{
                                            this.setState({
                                                changeQtyVisible:false,
                                            })
                                        }}>
                                            <Text style={{color:'black',fontSize:18}}>
                                                取消
                                            </Text>
                                        </TouchableOpacity>
                                        <TouchableOpacity style={styles.checkModalCenterRight} onPress={()=>{
                                            this.conditionRoom.qty = this.state.changeQtyNum;
                                        }}>
                                            <Text style={{color:'white',fontSize:18}}>
                                                确认
                                            </Text>
                                        </TouchableOpacity>
                                    </View>
                                </View>
                            </View>
                    </Modal>
                </View>
            </View>
        )
    };

    //模态关闭
    onRequestClose(){
        this.setState({
            changeQtyVisible: false,
        })
    }

    //显示房态盘
    showRoomListHtml(item,index){
        let html;
        let html_room;

        if( (!item['wuserid'] || item['wuserid']==='' || item.whsk_status ==="撤销" ) && this.selected_room.indexOf(item.room)<0 ){
            if(!this.state.showClean ? (item.hsk_status!=="CL"&&item.hsk_status!=="OS"&&item.hsk_status!=="OO"&&item.hsk_status!=="TU") : true ){
                if(!this.rooms.hasOwnProperty(item.room) && (this.state.synstatus === item['synstatus'] || this.state.synstatus==="ALL")){
                    if(!this.floors.hasOwnProperty(item.floor)){
                        if(this.state.flag === ''){
                            this.state.flag = item.room;
                        }
                        html = (
                            <View key={item.floor} style={styles.cellFloorView}>
                                <Text style={styles.cellFloorText}>
                                    {item.floor+'层'}
                                </Text>
                                <TouchableOpacity  activeOpacity={1} onPress={()=>{
                                    let select_rooms = this.state.select_rooms;
                                    let select_floors = this.state.select_floors;
                                    if(select_floors.indexOf(item.floor) >= 0){
                                        select_floors.splice(select_floors.indexOf(item.floor),1);
                                        for(let room in select_rooms){
                                            if(select_rooms[room]['floor'] === item.floor){
                                                delete select_rooms[room];
                                            }
                                        }
                                    }else{
                                        this.state.roomsArr.map((ii,index)=>{
                                            if( (!this.state.showClean ? (ii.hsk_status!=="CL"&&ii.hsk_status!=="OS"&&ii.hsk_status!=="OO"&&ii.hsk_status!=="TU") : true) && ii.floor === item.floor ){
                                                if(!select_rooms[ii.room]){
                                                    select_rooms[ii.room] = ii
                                                }
                                            }
                                        })
                                        select_floors.push(item.floor);
                                    }
                                    this.setState({
                                        select_rooms:select_rooms,
                                        select_floors:select_floors,
                                    })

                                }}>
                                    <Text style={styles.cellFloorBtn}>
                                        {
                                            // (this.floors[item.floor] && this.floors[item.floor]==="true") && (
                                            this.ifFloorCheck(item.floor)
                                            // )
                                        }
                                    </Text>
                                </TouchableOpacity>
                            </View>
                        );
                        this.floors[item.floor] = "false";

                        let css_extend = {};
                        if(this.state.select_rooms[item.room]){
                            css_extend = {borderColor:this.getNewColor(item.synbcolor)}
                        }
                        html_room = (
                            <TouchableOpacity activeOpacity={1}
                                              onPress={()=>{
                                                  this.changeSelect(item);
                                              }}
                                              onLongPress={()=>{
                                                  this.longPress(item);
                                              }}>
                                <View style={[styles.rightRoomBox,{backgroundColor:item.synbcolor,borderColor:item.synbcolor,borderWidth:2,},css_extend]}>
                                    <Text style={{color:item.syntcolor,fontSize:15}}>
                                        {item.room}
                                    </Text>
                                    {
                                        (this.state.flag === item.room)
                                        &&
                                        (
                                            <View style={{flex:1,justifyContent: 'flex-end',flexDirection: 'row'}}>
                                                <FontAwesome name={'flag'} size={17} style={{color: '#ff0000',marginRight:4,}}/>
                                            </View>
                                        )
                                    }
                                </View>
                            </TouchableOpacity>
                        )
                        this.rooms[item.room] = "false";

                    }else{
                        let css_extend = {};
                        if(this.state.select_rooms[item.room]){
                            css_extend = {borderColor:this.getNewColor(item.synbcolor)}
                        }
                        html_room = (
                            <TouchableOpacity activeOpacity={1}
                                              onPress={()=>{
                                                  this.changeSelect(item);
                                              }}
                                              onLongPress={()=>{
                                                  this.longPress(item);
                                              }}>
                                <View style={[styles.rightRoomBox,{backgroundColor:item.synbcolor,borderColor:item.synbcolor,borderWidth:2,},css_extend]}>
                                    <Text style={{color:item.syntcolor,fontSize:15}}>
                                        {item.room}
                                    </Text>
                                    {
                                        (this.state.flag === item.room)
                                        &&
                                        (
                                            <View style={{flex:1,justifyContent: 'flex-end',flexDirection: 'row'}}>
                                                <FontAwesome name={'flag'} size={17} style={{color: '#ff0000',marginRight:4,}}/>
                                            </View>
                                        )
                                    }
                                </View>
                            </TouchableOpacity>
                        )
                        this.rooms[item.room] = "false";
                    }
                }
            }
        }else{
            if(this.selected_room.indexOf(item.room)<0){
                this.selected_room.push(item.room)
            }
        }

        return [html,html_room]
    }

    showRoomStatusHtml(){
        let rmStatusJson = {'ALL':{"syntcolor":FONT_COLOR_SUB_TITLE,"synbcolor":'#FFFFFF',"number":0,}};
        let html = [];
        this.state.roomsArr.map((item,index)=>{
            if( (!item['wuserid'] || item['wuserid']==='' || item.whsk_status ==="撤销") && this.selected_room.indexOf(item.room)<0 ) {
                if (!this.state.showClean ? (item.hsk_status !== "CL" && item.hsk_status !== "OS" && item.hsk_status !== "OO" && item.hsk_status !== "TU") : true) {
                    if(rmStatusJson[item.synstatus]){
                        rmStatusJson[item.synstatus]['number'] = rmStatusJson[item.synstatus]['number']+1
                    }else{
                        rmStatusJson[item.synstatus] = {"syntcolor":item.syntcolor,"synbcolor":item.synbcolor,"number":1,}
                    }
                    rmStatusJson['ALL']['number'] = rmStatusJson['ALL']['number']+1
                }
            }
        })

        for(let synstatus in rmStatusJson){
            html.push(
                <TouchableOpacity activeOpacity={0.8}  onPress={() => {
                    this.setState({
                        synstatus : synstatus,
                    })
                }} underlayColor="#4a65ff">
                    <View style={{width:(SCREEN_WIDTH * 5/5-8)/4,height:40,alignItems: 'center',flexDirection: 'row',justifyContent: 'center',backgroundColor:rmStatusJson[synstatus]['synbcolor']}}>
                        <Text style={{fontSize:14,color:rmStatusJson[synstatus]['syntcolor']}}>
                            {synstatus}:{rmStatusJson[synstatus]['number']}
                            {
                                this.state.synstatus === synstatus && (
                                        <FontAwesome name={'star'} size={13} style={{color: '#f9f9f9',flex:1,justifyContent: 'flex-end',flexDirection: 'row',}}/>
                                )
                            }
                        </Text>
                    </View>
                </TouchableOpacity>
            )

        }

        return html

    }

    getNewColor(color){
        let ar = [];

        //分三组转换为10进制整数，然后减去255，取绝对值，再转换为16进制字符
        ar.push(Math.abs(parseInt('0x' + color.substr(1,2))-255).toString(16));
        ar.push(Math.abs(parseInt('0x' + color.substr(3,2))-255).toString(16));
        ar.push(Math.abs(parseInt('0x' + color.substr(5,2))-255).toString(16));
        //不足2位的补零  转换为大写
        for(let i in ar) {
            if (ar[i].length < 2) ar[i] = '0' + ar[i];
            ar[i] = ar[i].toUpperCase();
        }

        let newColor = '#' + ar.join('');
        newColor = '#dc1904';
        return newColor
    }

    //选择事件
    changeSelect(item){
        let select_rooms = this.state.select_rooms;
        if(select_rooms[item.room]){
            delete select_rooms[item.room]
        }else{
            select_rooms[item.room] = item;
        }
        this.setState({
            select_rooms:select_rooms,
        })
    }

    //长按事件
    longPress(item){
        this.setState({showConditionPop: !this.state.showConditionPop})
        this.conditionRoom = item
    }

    //楼层是否被选择
    ifFloorCheck(floor){
        let icon = (<Image style={{width: 20, height: 20}} source={require('../../../resource/login/quanxuan.png')}/>);
        if(this.state.select_floors.indexOf(floor)<0){
            icon = (<Image style={{width: 20, height: 20}} source={require('../../../resource/login/weixuan1.png')}/>);
        }
        return icon;
    };

    _openTypeDialog(){
        this.setState({showTypePop: !this.state.showTypePop})
    };

    _openAssDialog(){
        this.setState({showAssPop: !this.state.showAssPop})
    };

    _openWuseridDialog(){
        this.setState({showWuseridPop: !this.state.showWuseridPop})
    };

    //清洁人列表
    showWuser(item,index){
        let _this = this;
        return(
            <View key={index}>
                <TouchableOpacity activeOpacity={1} onPress={()=>{
                    let new_json = _this.state.view_wuserid
                    if(new_json[item.wuserid]==="true"){
                        new_json[item.wuserid] = "false"
                    }else{
                        new_json[item.wuserid] = "true"
                    }
                    _this.setState({
                        view_wuserid:new_json
                    })
                }}>
                    <View style={styles.boxHeader} >
                        <View style={styles.headerLeft}>
                            {
                                (this.state.view_wuserid[item.wuserid] === 'true')?(
                                    <AntDesign name={'caretdown'} size={16} style={{color: COLOR_FOCUS,marginLeft: 5}}/>
                                ):(
                                    <AntDesign name={'caretright'} size={16} style={{color: COLOR_FOCUS,marginLeft: 5}}/>
                                )
                            }
                            <Text style={styles.boxHeaderText}>
                                {item.wusername}
                            </Text>

                            {
                                (item.place_list_c!=="")&&(<MaterialIcons name={'place'} size={16} style={{color: COLOR_FOCUS,marginLeft: 10}}/>)
                            }

                            <Text style={styles.boxHeaderText} numberOfLines={1}>
                                {item.place_list_c}
                            </Text>
                        </View>
                        <TouchableOpacity activeOpacity={0.8} onPress={()=>{
                            this.addOneRoom(item.wuserid,item.qty_basis);
                        }}>
                            <View style={styles.boxHeaderBtn}>
                                <Text style={{color:COLOR_LINK}}>+1间</Text>
                            </View>
                        </TouchableOpacity>
                        <TouchableOpacity activeOpacity={0.8} onPress={()=>{
                            this.addBasicRoom(item.wuserid,item.qty_basis);
                        }}>
                            <View style={styles.boxHeaderBtn}>
                                <Text style={{color:COLOR_LINK}}>+标准</Text>
                            </View>
                        </TouchableOpacity>
                        <TouchableOpacity activeOpacity={0.8} onPress={()=>{
                            this.addAverageRoom(item.wuserid,item.qty_basis);
                        }}>
                            <View style={styles.boxHeaderBtn}>
                                <Text style={{color:COLOR_LINK}}>+均分</Text>
                            </View>
                        </TouchableOpacity>
                    </View>
                </TouchableOpacity>
                {
                    (this.state.view_wuserid[item.wuserid] === 'true')&&(
                        (this.state.room_wuserid[item.wuserid].length>0)
                            ?
                        (
                            <View  style={styles.boxContainer}>
                                {
                                    this.state.room_wuserid[item.wuserid].map((value,key)=>{
                                        return(
                                            this.showWuserRooms(value,key)
                                        )
                                    })

                                }
                            </View>
                        )
                            :
                        (
                            <View  style={[styles.boxContainer,{minHeight:100}]}>

                            </View>
                        )
                    )
                }
            </View>
        )
    };

    //+1间
    addOneRoom(wuserid,qty_basis){
        // console.log(JSON.stringify(this.state));
        let flag = this.state.flag;
        let room_wuserid = this.state.room_wuserid;
        let roomsArr = this.state.roomsArr;

        let ifReturn = 'no';
        for(let i = 0; i < roomsArr.length; i++ ){
            let item = roomsArr[i];

            if( (!item['wuserid'] || item['wuserid']==='' || item['whsk_status']==="撤销" ) && this.selected_room.indexOf(item.room)<0 ) {
                if (item.hsk_status !== "CL" && item.hsk_status !== "OS" && item.hsk_status !== "OO" && item.hsk_status !== "TU") {
                    if(ifReturn==='yes'){
                        flag = item.room;
                        break;
                    }

                    if(item.room===flag){
                        item['wuserid'] = wuserid;
                        room_wuserid[wuserid].push(item);
                        this.selected_room.push(item.room);
                        ifReturn='yes';
                        flag = '';
                    }
                }
            }
        }
        console.log("===="+JSON.stringify(room_wuserid))
        this.setState({
            room_wuserid: room_wuserid,
            select_rooms:{},
            flag:flag,
        })
    }

    //+标准
    addBasicRoom(wuserid,qty_basis){
        let flag = this.state.flag;
        let room_wuserid = this.state.room_wuserid;
        let roomsArr = this.state.roomsArr;

        let qty = 0;
        let start = 'no';
        room_wuserid[wuserid].map((item,index)=>{
            qty = qty + Number(item.qty)
        })

        for(let i = 0; i < roomsArr.length; i++ ){
            if(i+1 === roomsArr.length ){
                i=0
            }
            let item = roomsArr[i];

            if(item.room===flag || start==='yes'){
                start='yes';
                if( (!item['wuserid'] || item['wuserid']==='' || item['whsk_status']==="撤销"  ) && this.selected_room.indexOf(item.room)<0 ) {
                    if (item.hsk_status !== "CL" && item.hsk_status !== "OS" && item.hsk_status !== "OO" && item.hsk_status !== "TU") {
                        if(Number(qty)>=Number(qty_basis)){
                            flag = item.room;
                            console.log(i)
                            break;

                        }else{
                            qty = qty + Number(item.qty)
                            item['wuserid'] = wuserid;
                            room_wuserid[wuserid].push(item);
                            this.selected_room.push(item.room);
                        }
                    }
                }
            }
        }

        this.setState({
            room_wuserid: room_wuserid,
            select_rooms:{},
            flag:flag,
        })
    }

    //+均分
    addAverageRoom(wuserid,qty_basis){

        let flag = this.state.flag;
        let room_wuserid = this.state.room_wuserid;
        let roomsArr = this.state.roomsArr;

        let qty = 0;
        let start = 'no';
        room_wuserid[wuserid].map((item,index)=>{
            qty = qty + Number(item.qty)
        })

        let qty_avg = this.qty_avg;
        console.log(qty_avg);
        // for(let i = 0; i < roomsArr.length; i++ ){
        //     let item = roomsArr[i];
        //     // if( (!item['wuserid'] || item['wuserid']==='' ) && this.selected_room.indexOf(item.room)<0 ) {
        //         if (!this.state.showClean ? (item.hsk_status !== "CL" && item.hsk_status !== "OS" && item.hsk_status !== "OO") : true) {
        //             qty_avg = qty_avg + Number(item.qty)
        //         }
        //     // }
        // }
        // qty_avg = qty_avg/this.state.dailywuserid.length

        for(let i = 0; i < roomsArr.length; i++ ){
            if(i+1 === roomsArr.length ){
                i=0
            }
            let item = roomsArr[i];

            if(item.room===flag || start==='yes'){
                start='yes';
                if( (!item['wuserid'] || item['wuserid']===''  || item['whsk_status']==="撤销" ) && this.selected_room.indexOf(item.room)<0 ) {
                    if (item.hsk_status !== "CL" && item.hsk_status !== "OS" && item.hsk_status !== "OO" && item.hsk_status !== "TU") {
                        console.log(qty_avg)
                        if(Number(qty)>=Number(qty_avg)){
                            flag = item.room;
                            console.log(i)
                            break;

                        }else{
                            qty = qty + Number(item.qty)
                            item['wuserid'] = wuserid;
                            room_wuserid[wuserid].push(item);
                            this.selected_room.push(item.room);
                        }
                    }
                }
            }
        }

        this.setState({
            room_wuserid: room_wuserid,
            select_rooms:{},
            flag:flag,
        })
    }

    //显示清洁人房间
    showWuserRooms=(value,key)=>{

        return (
            <TouchableOpacity activeOpacity={0.9}  onPress={()=>{
                this.state.select_rooms = {}
                this.state.select_rooms[value.room] = value;
                this.setState({showWuseridPop: true})
                // this.props.$this.navigate('ChangeUseridScreen',{"orderid":this.props.orderid,"text":"更换清洁人","page":'AssignRoom',goBack:()=>{
                //
                // }});
            }} onLongPress={()=>{
                this.state.select_rooms = {}
                this.state.select_rooms[value.room] = value;

                if(value['orderid'] && value['orderid']!==""){
                    this._openAssDialog()
                }

            }}>
                <View style={[styles.leftRoomBox,{backgroundColor:value.synbcolor}]} >
                    <Text style={{color:value.syntcolor,fontSize:15}}>
                        {value.room}
                    </Text>
                </View>
            </TouchableOpacity>
        )
    }

}

const props = state => {
    return {
        onDailyOrderSweepDefault:state.onDailyOrderSweepDefault,
        onRetrieveRoomsViewAs:state.onRetrieveRoomsViewAs,
        onCache: state.onCache,
        onDailyOrderSweepSave:state.onDailyOrderSweepSave,
        onChangeSweepOrderStatus:state.onChangeSweepOrderStatus,
    }
};

export default AssignRoom = connect(props)(AssignRoom);